import sha1 from 'js-sha1'
import { getJsapiTicket } from '@/api/map'

var raw = function (args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });

  var string = '';
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k];
  }
  string = string.substr(1);
  return string;
};

const createNonceStr = function () {
  return Math.random().toString(36).substr(2, 15);
};

const createTimestamp = function () {
  return parseInt(new Date().getTime() / 1000) + '';
};


const injectPermission = async (isRefresh = 1) => {
  return new Promise((resolve, reject) => {
    // const jsApiTicketRes = await getJsapiTicket(isRefresh);
    // const JSAPI_TICKET = JSON.parse(jsApiTicketRes.data).ticket
    const JSAPI_TICKET = 'O3SMpm8bG7kJnF36aXbe8wZkBx4eoSkeojVaNMb6K_5L6BnxgYakjqrtY5uaNoVd3PoLCXnISs-FyVYamuRlmQ'
    window.JSAPI_TICKET = JSAPI_TICKET
    let config = {
      nonceStr: createNonceStr(),
      timestamp: createTimestamp(),
      url: location.href.split('#')[0],
      jsapi_ticket: JSAPI_TICKET
    }
    const str = raw(config)
    const signature = sha1(str)
    config = {
      ...config,
      signature,
      debug: true,
      // appId: 'wxdd35ae58e1093933',
      appId: 'wx9f78809361b8ccc2',
      jsApiList: ['postMessage', 'getLocation', 'checkJsApi', 'redirectTo'] // 必填，需要使用的JS接口列表
    }
    wx.config(config);
    wx.ready(() => {
      console.log('通过');
      resolve ()
    });
    wx.error(async (res) => {
      // alert (res)
      // injectPermission(2)
      console.error(res);
      reject (res)
    });
  })

}

const getLocation = () => {
  return new Promise((resolve, reject) => {
    try {
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          var speed = res.speed; // 速度，以米/每秒计
          var accuracy = res.accuracy; // 位置精度
          resolve(res)
        }
      })
    } catch (error) {
      console.error(error);
      reject(error)
    }
  })
}
export default injectPermission

export {
  getLocation
}
